﻿using RedisDemo.Entitys;
using RedisDemo.Redis.Base;
using RedisDemo.Service.IServices;
using RedisDemo.Service.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RedisDemo.Service.Service
{
    public class PanicBuyingService : IPanicBuyingService
    {
        private readonly IRepositoryWrapper _repository;
        private readonly RedisConfig _redis;

        public PanicBuyingService(IRepositoryWrapper repository, RedisConfig redis)
        {
            _repository = repository;
            _redis = redis;
        }

        public async Task<bool> InsertCommodity(long Num)
        {
            for (int i = 0; i < Num; i++)
            {
                var User = GenFu.GenFu.New<UserPanicBuying>();
                await _redis.ListRightPushAsync<UserPanicBuying>("秒杀", User);
            }
            var Count = await _redis.ListLengthAsync("秒杀");
            if (Count == Num)
                return true;
            return false;
        }

        public async Task<bool> PanicBuying(int Id)
        {
            var Count = await _redis.ListLengthAsync("秒杀");
            if (Count == 0)
            {
                Console.WriteLine($"抱歉,当前已没有库存。");
                return false;
            }
            else
            {
                await _redis.ListRightPopAsync<UserPanicBuying>("秒杀");
                Console.WriteLine($"用户{Id},已购买!");
                return true;
            }
            
        }
    }
}
